package com.ynet.middleground.user.service.impl;

import com.google.common.base.Throwables;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.user.bean.*;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.LoginLogMapper;
import com.ynet.middleground.user.dto.*;
import com.ynet.middleground.user.entity.LoginLog;
import com.ynet.middleground.user.model.UserModel;
import com.ynet.middleground.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: 2019-10-12_userCenter
 * @description: 用户管理模块实现类
 * @author: DaiGaoLe
 * @create: 2019-10-23 16:41
 **/

@Path("user")
@Produces({MediaType.APPLICATION_JSON + "; " + "charset=UTF-8", MediaType.TEXT_XML + "; " + "charset=UTF-8"})
@Api(value = "用户管理模块实现类", tags = {"用户管理模块实现类"})
@Service(timeout = 6000, version = "0.0.1")
public class UserServiceImpl implements UserService, GenericService {

    @Autowired
    UserModel userModel;

    @Autowired
    LoginLogMapper loginlogMapper;

    @POST
    @Path("registered")
    @ApiOperation(value = "用户注册服务(企业,自然人)", notes = "用户注册服务，包括企业客户、自然人客户")
    @Override
    public ServiceResult<Integer> registered(UserRegistrationReq requestObject) {
        ServiceResult<Integer> resultService = new ServiceResult<>();
        Integer userId = null;
        try {
            userId = userModel.registered(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(userId);
        // 打日志的系统工具
        IfpLogger.info("UserRegistrationServiceImp", "", "");
        return resultService;
    }

    @POST
    @Path("user-password-maintenance")
    @ApiOperation(value = "修改/重置密码维护服务入口(自然人,企业员工,港内员工)", notes = "修改/重置密码维护服务入口")
    @Override
    public ServiceResult<String> userPasswordMaintenance(UserPasswordMaintenanceReq requestObject) {
        ServiceResult<String> resultService = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.userPasswordMaintenance(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        // 打日志的系统工具
        IfpLogger.info("UserRegistrationServiceImp", "", "");
        resultService.setResult(result);
        return resultService;
    }

    @POST
    @Path("authentication")
    @ApiOperation(value = "用户认证服务(企业,自然人)", notes = "用户认证服务")
    @Override
    public ServiceResult<String> authenticationService(UserAuthentication requestObject) {
        ServiceResult<String> resultService = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.userAuthentication(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(result);
        return resultService;
    }

    @POST
    @Path("unlock")
    @ApiOperation(value = "加解锁定用户入口(企业、自然人、企业员工、港内员工)", notes = "加解锁定用户入口")
    @Override
    public ServiceResult<String> unlockOrLocksUser(UnlockOrLocksUserReq requestObject) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.unlockOrLocksUser(requestObject);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;
    }

    @POST
    @Path("info")
    @ApiOperation(value = "用户信息查看服务(企业、企业员工)", notes = "用户信息查看服务包括企业用户、企业操作人员")
    @Override
    public ServiceResult<List<UserInfoDto>> queryUserInfo(QueryUserInfoReq requestObject) {
        ServiceResult<List<UserInfoDto>> resultService = new ServiceResult<>();
        List<UserInfoDto> userInfoDtos = null;
        try {
            userInfoDtos = userModel.queryUserInfo(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setPagerInfo(requestObject.getPagerInfo());
        resultService.setResult(userInfoDtos);
        return resultService;
    }

    @POST
    @Path("queryNaturalPersonList")
    @ApiOperation(value = "自然人查询", notes = "自然人查询")
    @Override
    public ServiceResult<List<NaturalPersonDto>> queryNaturalPersonList(QueryNaturalPersonReq requestObject) {
        ServiceResult<List<NaturalPersonDto>> resultService = new ServiceResult<>();
        List<NaturalPersonDto> naturalPersonDtos = null;
        try {
            naturalPersonDtos = userModel.queryNaturalPersonList(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setPagerInfo(requestObject.getPagerInfo());
        resultService.setResult(naturalPersonDtos);
        return resultService;
    }

    @POST
    @Path("login")
    @ApiOperation(value = "登录验密服务实现类(自然人,企业员工,港内员工)", notes = "登录验密服务实现类")
    @Override
    public ServiceResult<Integer> loginVerification(LoginVerificationReq requestObject) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        Integer result = null;
        LoginLog loginLog = new LoginLog();
        loginLog.setChannel(requestObject.getChannel());
        loginLog.setGmtCreate(LocalDateTime.now());
        loginLog.setLoginType(requestObject.getOperationType());
        loginLog.setUserType(requestObject.getUserType());
        try {
            result = userModel.loginVerification(requestObject);
            loginLog.setLoginStatus(SystemConstant.LOGIN_SUCCESS_STATUS);
            loginLog.setUserId(result);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            loginLog.setLoginStatus(SystemConstant.LOGIN_FAIL_STATUS);
            loginLog.setReason(be.getMessage());
            loginlogMapper.insert(loginLog);
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            loginLog.setLoginStatus(SystemConstant.LOGIN_FAIL_STATUS);
            loginLog.setReason(ErrorMessageConstant.ECUC0000_MESSAGE);
            loginlogMapper.insert(loginLog);
            return serviceResult;
        }
        serviceResult.setResult(result);
        loginlogMapper.insert(loginLog);
        return serviceResult;
    }

    @POST
    @Path("invitation-code")
    @ApiOperation(value = "获取邀请码服务(企业,自然人)", notes = "获取邀请码服务，适应邀请注册业务场景")
    @Override
    public ServiceResult<String> getInvitationCode(InvitationCodeReq requestObject) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.getInvitationCode(requestObject);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;
    }

    @DELETE
    @Path("delete")
    @ApiOperation(value = "用户删除服务(企业、自然人、企业员工、港内员工)", notes = "删除用户服务入口包括企业客户、自然人客户、企业操作人员、港内员工")
    @Override
    public ServiceResult<String> deleteUser(DeleteUserReq requestObject) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.deleteUser(requestObject);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;
    }

    @POST
    @Path("change")
    @ApiOperation(value = "用户信息修改入口(企业员工,自然人)", notes = "用户信息修改入口包括企业操作人员、自然人用户")
    @Override
    public ServiceResult<String> changeUserInfo(ChangeUserInfoReq requestObject) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String returnsResult = null;
        try {
            returnsResult = userModel.changeUserInof(requestObject);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(returnsResult);
        return serviceResult;
    }

    @POST
    @Path("company-change")
    @ApiOperation(value = "企业用户信息修改入口(企业)", notes = "企业用户信息修改入口")
    @Override
    public ServiceResult<String> changeBasicInfo(ChangeUserInfoEnterpriseBasicInfo requestObject) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String returnsResult = null;
        try {
            returnsResult = userModel.changeBasicInfo(requestObject);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(returnsResult);
        return serviceResult;
    }

    @POST
    @Path("view-archives")
    @ApiOperation(value = "档案查看服务入口(企业、自然人)", notes = "档案查看服务入口")
    @Override
    public ServiceResult<ViewArchivesDto> viewArchives(ViewArchivesReq requestObject) {
        ServiceResult<ViewArchivesDto> serviceResult = new ServiceResult<>();
        ViewArchivesDto viewArchivesDto = null;
        try {
            viewArchivesDto = userModel.viewArchives(requestObject);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(viewArchivesDto);
        return serviceResult;
    }

    /*
     * @param requestObj
     * @return userId
     * @program: 2019-11-05
     * @author: Wangxz
     */
    @POST
    @Path("add-enterprise-user-info")
    @ApiOperation(value = "添加企业员工用户服务", notes = "添加企业员工用户服务，操作人字段与对应企业进行关联")
    @Override
    public ServiceResult<Integer> addEnterpriseUserInfo(AddEnterpriseUserInfoReq requestObj) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        try {
            Integer userId = userModel.addEnterpriseUserInfo(requestObj);
            serviceResult.setResult(userId);
        } catch (BusinessException e) {
            IfpLogger.info("addEnterpriseUserInfo", e.getCode() + ":" + e.getMessage());
            serviceResult.setError(e.getCode(), e.getMessage());
            return serviceResult;
        } catch (Exception e) {
            IfpLogger.error("addEnterpriseUserInfo", "执行添加企业员工用户异常,case:{}", Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        return serviceResult;
    }


    @POST
    @Path("user-authorization")
    @ApiOperation(value = "共有用户授权(企业,自然人)", notes = "渠道用户授权，不同渠道共有客户进行授权打标识")
    @Override
    public ServiceResult<String> channelUserAuthorization(ChannelUserAuthorizationReq requestObj) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.channelUserAuthorization(requestObj);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;

    }

    @POST
    @Path("user-formatId-authorization")
    @ApiOperation(value = "共有用户业态公司授权(企业,自然人)", notes = "业态公司授权，不同业态公司对共有客户进行授权打标识", hidden = true)
    @Override
    public ServiceResult<String> formatUserAuthorization(FormatUserAuthorizationReq requestObj) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.formatUserAuthorization(requestObj);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;

    }


    @POST
    @Path("get-user-name")
    @ApiOperation(value = "根据手机号或账号获取用户所属企业名和企业id", notes = "根据手机号或账号获取用户所属企业名和企业id")
    @Override
    public ServiceResult<List<EnterpriseListInfoDto>> pursuantTelephoneGetUserName(TelephoneGetUserNameReq requestObj) {
        ServiceResult<List<EnterpriseListInfoDto>> serviceResult = new ServiceResult<>();
        List<EnterpriseListInfoDto> result = null;
        try {
            result = userModel.pursuantTelephoneGetUserName(requestObj);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;
    }

    @POST
    @Path("supplement-invitation-code")
    @ApiOperation(value = "补录邀请码服务(企业,自然人)", notes = "补录邀请码服务")
    @Override
    public ServiceResult<String> supplementTheInvitationCode(SupplementInvitationCode requestObj) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.supplementTheInvitationCode(requestObj);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;
    }

    @POST
    @Path("info-by-user-name")
    @ApiOperation(value = "根据企业名称查询操作员用户信息及角色", notes = "根据企业名称查询操作员用户信息及角色(用户名、角色及渠道) ")
    @Override
    public ServiceResult<List<BaseicInfoAndRoleDTO>> getInfoByUserName(QueryBaseicInfoAndRoleReq requestObject) {
        ServiceResult<List<BaseicInfoAndRoleDTO>> resultService = new ServiceResult<>();
        List<BaseicInfoAndRoleDTO> userBaseInfoDtos = null;
        try {
            userBaseInfoDtos = userModel.getInfoByUserName(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setPagerInfo(requestObject.getPagerInfo());
        resultService.setResult(userBaseInfoDtos);
        return resultService;
    }

    @POST
    @Path("query-invitee-information")
    @ApiOperation(value = "根据邀请码查询邀请信息", notes = "根据邀请码查询邀请信息")
    @Override
    public ServiceResult<InviteeInformationDTO> queryInviteeInformation(QueryInviteeInformationReq requestObject) {
        ServiceResult<InviteeInformationDTO> resultService = new ServiceResult<>();
        InviteeInformationDTO inviteeInformationDTO = null;
        try {
            inviteeInformationDTO = userModel.queryInviteeInformation(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setResult(inviteeInformationDTO);
        return resultService;
    }

    @POST
    @Path("bind-dingtalk")
    @ApiOperation(value = "绑定钉钉账号-内部使用", notes = "绑定钉钉账号-内部使用")
    @Override
    public ServiceResult<String> bindDingTalk(BindDingDingReq requestObj) {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        String result = null;
        try {
            result = userModel.bindDingTalk(requestObj);
        } catch (BusinessException be) {
            serviceResult.setError(be.getCode(), be.getMessage());
            return serviceResult;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            serviceResult.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return serviceResult;
        }
        serviceResult.setResult(result);
        return serviceResult;
    }

    @POST
    @Path("query-factors-record")
    @ApiOperation(value = "查询企业四要素、个人两要素修改记录", notes = "查询企业四要素、个人两要素修改记录",hidden = true)
    @Override
    public ServiceResult<List<FactorsModifyRecordDto>> queryFactorsModifyRecord(QueryFactorsModifyRecordReq requestObject) {
        ServiceResult<List<FactorsModifyRecordDto>> resultService = new ServiceResult<>();
        List<FactorsModifyRecordDto> factorsModifyRecords = null;
        try {
            factorsModifyRecords = userModel.queryFactorsModifyRecord(requestObject);
        } catch (BusinessException be) {
            resultService.setError(be.getCode(), be.getMessage());
            return resultService;
        } catch (Exception e) {
            // 获取当前方法名
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "case: {}",
                    Throwables.getStackTraceAsString(e));
            resultService.setError(ErrorMessageConstant.ECUC0000_CODE, ErrorMessageConstant.ECUC0000_MESSAGE);
            return resultService;
        }
        resultService.setPagerInfo(requestObject.getPagerInfo());
        resultService.setResult(factorsModifyRecords);
        return resultService;
    }
}
